<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="出/入库单编号" prop="storageId">
        <el-input v-model="queryParams.storageId" placeholder="请输入出/入库单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="日期" prop="storageTime">
        <!-- <el-date-picker clearable v-model="queryParams.finaDate" type="date" value-format="yyyy-MM-dd" placeholder="日期">
        </el-date-picker> -->
        <el-date-picker type="daterange" v-model="storageTime" format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd" :style="{width: '100%'}" start-placeholder="开始日期" end-placeholder="结束日期"
                  range-separator="至" clearable></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleSync"
          v-hasPermi="['mes:reco:repo:sync']"
        >数据同步</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 主表数据表格 -->
    <el-table v-loading="loading" :data="repoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="70" align="center" />
      <el-table-column label="出/入库单编号" align="center"  width="200" prop="storageId">
        <template slot-scope="scope">
          <el-link type="primary" @click="showDetail(scope.row.storageId)">  {{ scope.row.storageId }}  </el-link>
        </template>
      </el-table-column>
      <el-table-column label="采购单号" align="center" width="200" prop="purcOrderCode" />
      <el-table-column label="出/入库日期" width="180" prop="storageTime">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.storageTime) }}
          </template>
      </el-table-column>
      <el-table-column label="出/入库" align="center" prop="recoCondition" />
      </el-table-column>
      <el-table-column label="对账类型" align="center" prop="recoType" />
      <el-table-column label="仓管确认" align="center" prop="confName" />
      <el-table-column label="审核状态" align="center" prop="auditStatus">
        <template slot-scope="scope">
          <span v-if="scope.row.auditStatus === '已审核'" style="color: gray;">已审核</span>
          <el-button
            v-else
            size="mini"
            type="text"
            @click="handleReview(scope.row)"
          >审核</el-button>
        </template>
      </el-table-column>
      <el-table-column label="审核员" align="center" prop="auditName" />
      </el-table-column>
      <el-table-column label="审核时间" width="180" align="center" prop="auditDate">
        <template slot-scope="scope">
           {{ formatDateTime(scope.row.auditTime) }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="对账日期" align="center" prop="recoTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recoTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="对账员" align="center" prop="recoName" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <span v-if="scope.row.auditStatus === '已审核' && scope.row.recoStatus === '未对账'" style="cursor: pointer; color: blue;" @click="showDetail(scope.row.storageId)">未对账</span>
          <span v-else-if="scope.row.recoStatus === '已完成'" style="color: gray;">已完成</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 子表对话框 -->
    <el-dialog :title="detailTitle" :visible.sync="detailVisible" width="80%" append-to-body>
      <el-table
        v-loading="childLoading"
        :data="repoDetailList"
        row-key="serialNum"
      >
        <el-table-column label="出/入库单编号" width="200" prop="storageId"></el-table-column>
        <el-table-column label="出/入库日期" width="180" prop="storageTime">
            <template slot-scope="scope">
              {{ formatDateTime(scope.row.storageTime) }}
            </template>
        </el-table-column>
        <el-table-column label="出/入库" align="center" prop="recoCondition" />
        <el-table-column label="对账类型" align="center" prop="recoType" /></el-table-column>
        <el-table-column label="物料名称" width="200" align="center" prop="itemName" />
        <el-table-column label="物料编码" width="180" align="center" prop="itemCode" />
        <el-table-column label="出/入库数量" width="120" align="center" prop="itemNum" />
        <el-table-column label="单价" width="120" align="center" prop="itemUnitPrice" />
                <el-table-column label="单位" width="80" align="center" prop="itemUnit" />
                <el-table-column label="入库金额" width="120" align="center" prop="itemInPrice" />
                <el-table-column label="出库金额" width="120" align="center" prop="itemOutPrice" />
                <el-table-column label="仓管确认" width="120" align="center" prop="confName" />
        <el-table-column label="审核人" width="120" align="center" prop="auditName" />
        <el-table-column label="审核状态" width="120" align="center" prop="auditStatus">
          <template slot-scope="scope">
            <span v-if="scope.row.auditStatus === '已审核'">已审核</span>
            <span v-else>未审核</span>
          </template>
        </el-table-column>
        <el-table-column label="审核时间" width="180" align="center" prop="auditDate">
          <template slot-scope="scope">
             {{ formatDateTime(scope.row.auditTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.auditStatus === '已审核' && scope.row.recoStatus !== '已对账'"
              size="mini"
              type="text"
              @click="handleReconciliation(scope.row)"
            >对账</el-button>
            <span v-else-if="scope.row.recoStatus === '已对账'" style="color: gray;">已对账</span>
          </template>
        </el-table-column>
        <el-table-column label="对账日期" width="180" align="center" prop="recoTime" />
        <el-table-column label="对账人" width="120" align="center" prop="recoName" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关闭</el-button>
          <el-button
               type="primary"
               @click="handleReconciliationByStorageId"
               v-if="repoDetailList.length > 0 && repoDetailList.every(row => row.auditStatus === '已审核')"
             >对账</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getRecoRepo, getRecoRepoDetail, reviewStep, reviewStep2, recoStep, finaRecoRepoSync,recoStepByStorageId } from "@/api/mes/ckdz";
import moment from 'moment'; // 引入 moment 库用于时间格式化

export default {
  data() {
    return {
      repoList: [], // 主表数据
      repoDetailList: [], // 子表数据
      detailVisible: false, // 子表对话框是否显示
      detailTitle: '', // 子表对话框标题
      loading: false, // 主表加载状态
      childLoading: false, // 子表加载状态
      storageTime: [],
      queryParams: { // 查询参数
        pageNum: 1,
        pageSize: 10,
        storageId: undefined, // 出/入库单编号
        storageTimeStart: null,
        storageTimeEnd: null,
      },
      total: 0, // 数据总数
      showSearch: true, // 是否显示搜索表单
    };
  },
  methods: {
    /** 获取主表数据 */
    getList() {
    this.loading = true;
    if (this.storageTime && this.storageTime.length > 0) {
      this.queryParams.storageTimeStart = this.storageTime[0];
      this.queryParams.storageTimeEnd = this.storageTime[1];
    } else {
      this.queryParams.storageTimeStart = null;
      this.queryParams.storageTimeEnd = null;
    }
    getRecoRepo(this.queryParams).then(response => {
      if (response.code === 200) {
        this.repoList = response.rows; // 主表数据
        this.total = response.total; // 数据总数
      } else {
        this.repoList = [];
        this.total = 0;
      }
    }).catch(() => {
      this.repoList = [];
      this.total = 0;
    }).finally(() => {
      this.loading = false;
    });
  },

    /** 显示子表数据 */
    showDetail(storageId) {
      this.detailTitle = '子表详情';
      this.childLoading = true;
      getRecoRepoDetail(storageId).then(response => {
        if (response.code === 200 && response.rows) {
          this.repoDetailList = response.rows;
        } else {
          this.repoDetailList = [];
        }
        this.childLoading = false;
        this.detailVisible = true;
      }).catch(() => {
        this.childLoading = false;
      });
    },

    /** 审核主表数据 */
    handleReview(row) {
      this.$modal.confirm('是否确认审核？').then(() => {
        reviewStep(row).then(response => {
          if (response.code === 200) {
            this.$modal.msgSuccess("审核成功");
            // 调用 reviewSubTable 来执行子表审核
            this.reviewSubTable(row.storageId);
            this.getList(); // 刷新主表数据
          } else {
            this.$modal.msgError("审核失败");
          }
        }).catch(() => {
          this.$modal.msgError("审核失败");
        });
      }).catch(() => {});
    },

    /** 审核子表数据 */
    reviewSubTable(storageId) {
      // 获取子表数据
      getRecoRepoDetail(storageId).then(response => {
        if (response.code === 200 && response.rows) {
          const subTableRows = response.rows;
          // 遍历子表数据并调用 reviewStep2 进行审核
          subTableRows.forEach(subTableRow => {
            reviewStep2(subTableRow).then(subResponse => {
              if (subResponse.code === 200) {
                this.$modal.msgSuccess("子表审核成功");
              } else {
                this.$modal.msgError("子表审核失败");
              }
            }).catch(() => {
              this.$modal.msgError("子表审核失败");
            });
          });
        } else {
          this.$modal.msgError("获取子表数据失败");
        }
      }).catch(() => {
        this.$modal.msgError("获取子表数据失败");
      });
    },

    /** 对账子表数据 */
    handleReconciliation(row) {
      this.$modal.confirm('是否确认对账？').then(() => {
        recoStep(row).then(response => {
          if (response.code === 200) {
            this.$modal.msgSuccess("对账成功");
            this.showDetail(row.storageId); // 刷新子表数据
            this.getList(); // 刷新主表数据
          } else {
            this.$modal.msgError("对账失败");
          }
        }).catch(() => {
          this.$modal.msgError("对账失败");
        });
      }).catch(() => {});
    },
    /** 根据出入库编码对账 */
        handleReconciliationByStorageId() {
          if (this.repoDetailList.length === 0) {
            this.$modal.msgError("没有子表数据");
            return;
          }

          this.$modal.confirm('是否确认根据出入库编码对账？').then(() => {
            recoStepByStorageId(this.repoDetailList).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("对账成功");
                this.showDetail(this.repoDetailList[0].storageId); // 刷新子表数据
                this.getList(); // 刷新主表数据
              } else {
                this.$modal.msgError("对账失败");
              }
            }).catch(() => {
              this.$modal.msgError("对账失败");
            });
          }).catch(() => {});
        },

    /** 同步数据按钮操作 */
    handleSync() {
      if (this.loading) {
        this.$modal.message("正常进行中，请不要重复点击...");
        return;
      }
      this.loading = true;
      this.$modal.confirm('是否确认同步数据？').then(() => {
        finaRecoRepoSync().then(response => {
          if (response.code === 200) {
            this.$modal.msgSuccess("同步成功");
            this.getList(); // 刷新主表数据
          } else {
            this.$modal.msgError("同步失败");
          }
        }).catch(() => {
          this.$modal.msgError("同步失败");
        }).finally(() => {
          this.loading = false;
        });
      }).catch(() => {
        this.loading = false;
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('md/repo/export', {
        ...this.queryParams
      }, `repo_${new Date().getTime()}.xlsx`);
    },

    /** 搜索方法 */
    handleQuery() {
      this.queryParams.pageNum = 1; // 搜索时重置分页
      this.getList();
    },

    /** 重置方法 */
    resetQuery() {
      this.resetForm("queryForm"); // 调用 Element UI 的 resetFields 方法
      this.handleQuery(); // 重置后重新加载数据
    },

    /** 时间格式化 */
    parseTime(time, cFormat) {
      return time ? moment(time).format(cFormat) : '';
    },

    /** 日期格式化 */
    formatDateTime(date) {
      return date ? moment(date).format('YYYY-MM-DD') : '';
    }
  },
  created() {
    this.getList(); // 页面加载时获取主表数据
  }
};

</script>
